//
//  HttpRequestTool.swift
//  CJPWB
//
//  Created by 陈锦彭 on 16/3/15.
//  Copyright © 2016年 chenjinpeng. All rights reserved.
//

import UIKit
import AFNetworking

enum requestType : String {
    case GET = "GET"
    case POST = "POST"
}


class HttpRequestTool: AFHTTPSessionManager {
    //设计单例
    static let shareInstance : HttpRequestTool = {
        let tool = HttpRequestTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()

}


// MARK: - 基本的网络请求工具
extension HttpRequestTool {

    func request(methodType : requestType, urlStr : String, parameters : [String : AnyObject], finished : (success : AnyObject?, error : NSError?) -> ()) {
        
        //成功回调的闭包
        let sucessCallBack = { (task : NSURLSessionDataTask, reslut : AnyObject?) -> Void in
            finished(success: reslut, error: nil)
            
        }
        
        //失败回调的闭包
        let errorCallBack = { (task : NSURLSessionDataTask?, error : NSError) -> Void in
            finished(success: nil, error: error)
        }
        
        if methodType == .GET {
            //GET请求
            GET(urlStr, parameters: parameters, progress: nil, success: sucessCallBack, failure: errorCallBack)
        }else {
            //POST请求
            POST(urlStr, parameters: parameters, progress: nil, success: sucessCallBack, failure: errorCallBack)
        }
    }     

}


// MARK: - 包装网络请求
extension HttpRequestTool {
      ///获取access token
    func requestAccessToken(code : String, finished : (successed : [String : AnyObject]?, error : NSError?) -> ()) {
        //4.1设置请求参数
        let params = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        //4.2发送请求
        HttpRequestTool.shareInstance.request(.POST, urlStr: "https://api.weibo.com/oauth2/access_token", parameters: params) { (success, error) -> () in
            finished(successed: success as? [String : AnyObject], error: error)
        }

    }
}

// MARK: - 加载首页数据
extension HttpRequestTool {
    ///加载首页数据
    func loadStatuses(since_id : Int, max_id : Int, finished : (isSuccess : [[String : AnyObject]]?, error : NSError?) -> ()) {
        //1.获取url
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //2.设置请求参数
        guard let accessToken = UserAccountViewModel.shareInstance.account?.access_token else {
            return
        }
        let parms : [String : AnyObject] = ["access_token" : accessToken, "since_id" : since_id, "max_id" : max_id]
        print(accessToken)
        //3.发送请求
        request(.GET, urlStr: urlStr, parameters: parms) { (success, error) -> () in
            //下载失败
            guard let result = success as? [String : AnyObject] else {
                finished(isSuccess: nil, error: error)
                return
            }
            //加载成功
            finished(isSuccess: result["statuses"] as? [[String : AnyObject]], error: nil)
        }
    }

}

// MARK: -发送文字微博
extension HttpRequestTool {
    ///发送文字微博
    func sendStatus(textString : String, image : UIImage?, finished : (isSuccessed : Bool) -> ()) {
        
        //2.设置参数
        let parms = ["access_token" : (UserAccountViewModel.shareInstance.account?.access_token)!, "status" : textString]
        //3.发送网络请求
        if image == nil {
            //1.创建url
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        request(.POST, urlStr: urlStr, parameters: parms) { (success, error) -> () in
            if error != nil {
            finished(isSuccessed: false)
             print(error)
            return
            }
             finished(isSuccessed: true)
            }
        }else {
            //请求的url
        let urlStr = "https://api.weibo.com/2/statuses/upload.json"
            
         //发送请求
        POST(urlStr, parameters: parms, constructingBodyWithBlock:  { (formData) -> Void in
                if let data = UIImageJPEGRepresentation(image!, 0.2) {
                    //请求体拼接上图片数据
                    formData.appendPartWithFileData(data, name: "pic", fileName: "123.png", mimeType: "image/png")
                }
                }, progress: nil, success:  { (_, result) -> Void in
                    if result != nil {
                        finished(isSuccessed: true)
                    }
                }, failure: { (_, result) -> Void in
                    print(result)
                    finished(isSuccessed: false)
            })
        }
    }
}













